import 'dart:async';
import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:ls_work/common/common.dart';
import 'package:ls_work/config/global_configs.dart';
import 'package:ls_work/login/login_router.dart';
import 'package:ls_work/net_configs.dart';
import 'package:ls_work/permission/permission_request.dart';
import 'package:ls_work/routers/fluro_navigator.dart';
import 'package:ls_work/ui/new_yyt_page.dart';
import 'package:ls_work/ui/pc300_test_page.dart';
import 'package:ls_work/util/log_utils.dart' as log;
import 'package:ls_work/util/request_url_utils.dart';
import 'package:ls_work/util/show_policy_dialog.dart';
import 'package:ls_work/widgets/load_image.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:ls_work/routers/routers.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:permission_handler/permission_handler.dart';

import '../login/page/user_manager.dart';
import '../login/user_permission_data.dart';
import '../net/HttpUtil.dart';
import '../net/api/http_api.dart';
// import 'package:rxdart/rxdart.dart';

class SplashPage extends StatefulWidget {
  @override
  _SplashPageState createState() => _SplashPageState();
}

class _SplashPageState extends State<SplashPage> {
  // int _status = 0;
  // List<String> _guideList = ["app_start_1", "app_start_2", "app_start_3"];
  StreamSubscription? _subscription;

  @override
  void initState() {
    super.initState();

    // SystemChrome.setPreferredOrientations([
    //   DeviceOrientation.portraitUp,
    //   DeviceOrientation.portraitDown,
    // ]);

    WidgetsBinding.instance.addPostFrameCallback((_) async {
      log.Log.init();

      var packageInfo = await PackageInfo.fromPlatform();
      await SpUtil.getInstance();
      UserManager.instance.init();
      SpUtil.putString(Constant.locaVersion, packageInfo.version);

      // print('🍎${SpUtil.getString(Constant.cookie)}');
      // if (SpUtil.getBool(Constant.key_guide, defValue: true)) {
      //   /// 预先缓存图片，避免直接使用时因为首次加载造成闪动
      //   _guideList.forEach((image) {
      //     precacheImage(ImageUtils.getAssetImage(image), context);
      //   });
      // }
      // _initSplash();

      await GlobalConfigs.init();
      if(GlobalConfigs.hasShowPolicy|| !GlobalConfigs.needShowPolicy){
        await _initNet();
      }else{
        showPolicyDialog(context,onApplyClick: (){
          GlobalConfigs.saveShowPolicy(true);
          Go().pop();
          _initNet();
        },onCancelClick: (){
          Go().pop();
          SystemNavigator.pop();
        });
      }

    });
  }

  Future<void> _initNet() async {
    HttpUtil.instance;
    try{
      await RequestUrlUtils.requestUrl();
    }catch(e){

    }
    RequestUrlUtils.init(debug: type==UrlType.LOCAL);
    RequestUrlUtils.findUrl(RequestUrlUtils.code);
    // requestPermission();
    await UserPermissionData().init();
    _initSplash();
  }

  @override
  void dispose() {
    _subscription?.cancel();
    print('dispose');
    // SystemChrome.setPreferredOrientations([
    //   DeviceOrientation.landscapeRight,
    //   DeviceOrientation.landscapeLeft,
    //   DeviceOrientation.portraitUp,
    //   DeviceOrientation.portraitDown,
    // ]);
    super.dispose();
  }

  // void _initGuide() {
  //   setState(() {
  //     _status = 1;
  //   });
  // }

  var permissions = [
    // Permission.camera,
    // Permission.storage,
    // Permission.microphone,
    // Permission.location,
    // Permission.locationWhenInUse,
    // Permission.locationAlways,
    // Permission.bluetoothScan,
    // Permission.bluetoothConnect,
    // Permission.bluetooth,
  ];

  Future<void> requestPermission() async {
    // if (await PermissionRequest.isLackPermissions(permissions)) {
    //   await PermissionRequest.requestPermissions(permissions);
    //   _initSplash();
    // } else {
    //   _initSplash();
    // }
  }

  void _initSplash() {
    // _subscription = //Observable
    // Future.delayed(Duration(milliseconds: 1500)).listen((_) {});
    // Future.delayed(Duration(milliseconds: 500), () {
    //
    // });
    if (SpUtil.getBool(Constant.login_islogin)??false) {
      NavigatorUtils.push(context, Routes.inithome, clearStack: true);
      // Go().pushAndPop(NewYytPage());
    } else {
      _goLogin();
    }
  }

  _goLogin() {
    NavigatorUtils.push(context, LoginRouter.loginPage, replace: true);
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      child:
      LoadAssetImage(
        GlobalConfigs.splashImage,
        fit: BoxFit.fill,
        format: "jpg",
        height: double.infinity,
        width: double.infinity,
      ),
      // Image.asset(
      //   ImageUtils.getImgPath("start_page1"),
      //   width: double.infinity,
      //   fit: BoxFit.fill,
      //   height: double.infinity,
      // ),
    );
  }
}
